#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
深度调试福特配置流程的脚本
"""

import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

def deep_debug_ford_config():
    """深度调试福特网站配置流程"""
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    
    # 设置User-Agent
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
    
    # 初始化WebDriver
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print("🔍 深度调试福特网站配置流程...")
        
        # 访问页面
        url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-D3&paint=PN4A7&planId=c"
        driver.get(url)
        time.sleep(5)
        
        print(f"初始URL: {driver.current_url}")
        
        # 查找Titanium车型
        titanium_element = None
        model_elements = driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
        
        for element in model_elements:
            data_cy = element.get_attribute('data-cy')
            if data_cy == 'Titanium' and element.is_displayed():
                titanium_element = element
                break
        
        if not titanium_element:
            print("❌ 未找到Titanium车型元素")
            return False
        
        print(f"✅ 找到Titanium车型元素")
        
        # 滚动到元素
        driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", titanium_element)
        time.sleep(1)
        
        # 获取点击前的状态
        before_url = driver.current_url
        before_title = driver.title
        before_nav_elements = driver.find_elements(By.CSS_SELECTOR, '[data-testid*="Navigation"], nav')
        before_nav_texts = [elem.text.strip() for elem in before_nav_elements if elem.text.strip()]
        
        print(f"点击前状态:")
        print(f"  URL: {before_url}")
        print(f"  Title: {before_title}")
        print(f"  导航元素数: {len(before_nav_elements)}")
        print(f"  导航文本: {before_nav_texts}")
        
        # 点击整个车型卡片
        print(f"\n🖱️  点击Titanium车型卡片...")
        driver.execute_script("arguments[0].click();", titanium_element)
        time.sleep(5)  # 等待更长时间
        
        # 获取点击后的状态
        after_url = driver.current_url
        after_title = driver.title
        after_nav_elements = driver.find_elements(By.CSS_SELECTOR, '[data-testid*="Navigation"], nav')
        after_nav_texts = [elem.text.strip() for elem in after_nav_elements if elem.text.strip()]
        
        print(f"点击后状态:")
        print(f"  URL: {after_url}")
        print(f"  Title: {after_title}")
        print(f"  导航元素数: {len(after_nav_elements)}")
        print(f"  导航文本: {after_nav_texts}")
        
        # 分析变化
        url_changed = after_url != before_url
        title_changed = after_title != before_title
        nav_changed = after_nav_texts != before_nav_texts
        
        print(f"\n📊 变化分析:")
        print(f"  URL变化: {url_changed}")
        print(f"  标题变化: {title_changed}")
        print(f"  导航变化: {nav_changed}")
        
        # 检查是否有Ford配置导航的特征
        ford_config_keywords = ['Model', 'Drive', 'Bodystyle', 'Colour', 'Interior', 'Extras', 'Summary']
        
        for nav_text in after_nav_texts:
            keyword_count = len([keyword for keyword in ford_config_keywords if keyword in nav_text])
            if keyword_count >= 4:
                print(f"✅ 检测到Ford配置导航: {nav_text}")
                print(f"   包含关键词数: {keyword_count}")
                return True
        
        # 检查是否出现了任何配置相关的页面元素
        config_selectors = [
            '[class*="configurator"]',
            '[class*="config"]',
            '[data-testid*="config"]',
            '[data-cy*="config"]',
            '.simplebar-content',  # 颜色选择器的容器
        ]
        
        print(f"\n🔍 检查配置相关元素:")
        for selector in config_selectors:
            elements = driver.find_elements(By.CSS_SELECTOR, selector)
            if elements:
                print(f"  找到 {len(elements)} 个 '{selector}' 元素")
                for i, elem in enumerate(elements[:3]):  # 只显示前3个
                    if elem.is_displayed():
                        elem_text = elem.text.strip()[:100]  # 只显示前100字符
                        print(f"    {i+1}. 可见元素: {elem_text}")
        
        # 尝试查找颜色相关的元素
        print(f"\n🌈 检查颜色选择器元素:")
        colour_selectors = [
            'div[role="radio"][class*="ColoursSection__ColourItemWrapper"]',
            '[aria-label*="Red"]',
            '[aria-label*="Blue"]',
            '[aria-label*="Black"]',
            '[aria-label*="White"]',
        ]
        
        for selector in colour_selectors:
            elements = driver.find_elements(By.CSS_SELECTOR, selector)
            if elements:
                print(f"  找到 {len(elements)} 个 '{selector}' 元素")
                for i, elem in enumerate(elements[:3]):
                    if elem.is_displayed():
                        aria_label = elem.get_attribute('aria-label')
                        print(f"    {i+1}. aria-label: {aria_label}")
        
        return False
        
    except Exception as e:
        print(f"调试过程出错: {e}")
        return False
        
    finally:
        input("按Enter键关闭浏览器...")
        driver.quit()

if __name__ == "__main__":
    deep_debug_ford_config()
